package com.yourenbang.lingyun.transaction.job.handler;

import com.alibaba.fastjson.JSON;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.yourenbang.lingyun.constants.enums.pay.PayTypeEnum;
import com.yourenbang.lingyun.core.util.DingdingUtils;
import com.yourenbang.lingyun.domain.PayChannel;
import com.yourenbang.lingyun.domain.PayChannelExample;
import com.yourenbang.lingyun.mapper.PayChannelMapper;
import com.yourenbang.lingyun.transaction.config.DingdingConfig;
import com.yourenbang.lingyun.transaction.mapper.TransactionPayTypeMapper;
import com.yourenbang.lingyun.transaction.web.domain.vo.pay.BalanceAlarmDTO;
import com.yourenbang.lingyun.transaction.web.service.pay.withdraw.channel.FuSuiLingGongService;
import com.yourenbang.lingyun.transaction.web.service.pay.withdraw.channel.YunHuiSuanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;


/**
 * 余额钉钉提醒
 */
@Component
@Slf4j
public class BalanceAlarmHandler {

    private static final String PAY_CHANNEL_NAME_YUNHUISUAN = "云汇算代付";
    private static final String PAY_CHANNEL_NAME_FUSUILINGGONG = "福穗灵工";
    private static final String DEVELOPER_PHONE = "15101061697";

    @Resource
    private DingdingConfig dingdingConfig;
    @Resource
    private PayChannelMapper payChannelMapper;
    @Autowired
    private TransactionPayTypeMapper transactionPayTypeMapper;
    @Resource
    private YunHuiSuanService yunHuiSuanService;
    @Resource
    private FuSuiLingGongService fuSuiLingGongService;

    /**
     * 余额预警定时任务
     * 测试 {@see  }
     *
     * @see BalanceAlarmHandler
     */
    @XxlJob("balanceAlarmHandler")
    public ReturnT<String> balanceAlarmHandler(String param) {

        XxlJobLogger.log("【余额预警】任务开始。。。，入参：{}", param);

        BalanceAlarmDTO balanceAlarmDTO = JSON.parseObject(param, BalanceAlarmDTO.class);


        PayChannelExample payChannelExample = new PayChannelExample();
        payChannelExample.createCriteria().andNameEqualTo(balanceAlarmDTO.getPayChannelName())
                .andPlatNoEqualTo(balanceAlarmDTO.getPlatNo());
        List<PayChannel> payChannelList = payChannelMapper.selectByExample(payChannelExample);
        if (CollectionUtils.isEmpty(payChannelList)) {
            XxlJobLogger.log("未找到渠道，入参：{}", balanceAlarmDTO.getPayChannelName());
            return ReturnT.FAIL;
        }

        Integer payChannelId = payChannelList.get(0).getPayChannelId();
        List<String> mobiles = balanceAlarmDTO.getMobiles();
        if (CollectionUtils.isEmpty(mobiles)) {
            mobiles = Lists.newArrayList();
            mobiles.add(DEVELOPER_PHONE);
        }

        //
        BigDecimal balanceAmount = getBalance(balanceAlarmDTO);
        if (Objects.isNull(balanceAmount)) {
            XxlJobLogger.log("查询余额失败，入参：{}", JSON.toJSONString(balanceAlarmDTO));
            return ReturnT.FAIL;
        }

        //余额不足关闭
        if (Objects.nonNull(balanceAlarmDTO.getCloseAlarmAmount()) &&
                balanceAmount.compareTo(balanceAlarmDTO.getCloseAlarmAmount()) < 0) {

            closePayChannel(payChannelId, balanceAlarmDTO, mobiles);

            return ReturnT.SUCCESS;
        }

        //余额不足报警
        if (Objects.nonNull(balanceAlarmDTO.getBalanceAlarmAmount()) &&
                balanceAmount.compareTo(balanceAlarmDTO.getBalanceAlarmAmount()) < 0) {

            String msg = "[友仁帮]【账户余额不足预警】" + balanceAlarmDTO.getPayChannelName() + "-账户剩余[" + balanceAmount + "]元,请尽快充值!";
            DingdingUtils.sendToDingdingAtMobiles(msg, dingdingConfig.getDingdingPushYjgtToken(), mobiles);

        }


        return ReturnT.SUCCESS;
    }


    /**
     * 关闭代付渠道
     *
     * @param payChannelId    payChannelId
     * @param balanceAlarmDTO balanceAlarmDTO
     * @param mobiles         mobiles
     * @return ReturnT<String>
     */
    private void closePayChannel(Integer payChannelId, BalanceAlarmDTO balanceAlarmDTO, List<String> mobiles) {

        //关闭支付方式
        transactionPayTypeMapper.closePayTypeByChannelId(payChannelId);
        transactionPayTypeMapper.closePayTypeByCodeNeedPlatNo(PayTypeEnum.BANK_CARD_PAY.getCode(), balanceAlarmDTO.getPlatNo());

        //发送钉钉报警
        String message = "[友仁帮]【账户余额不足预警】余额低于关闭阈值,已关闭支付渠道:" + balanceAlarmDTO.getPayChannelName() + ",请尽快充值!";
        DingdingUtils.sendToDingding(message, dingdingConfig.getDingdingWarnToken());
        DingdingUtils.sendToDingdingAtMobiles(message, dingdingConfig.getDingdingPushYjgtToken(), mobiles);

    }


    /**
     * 获取代付渠道余额,单位元
     *
     * @param balanceAlarmDTO
     * @return
     */
    private BigDecimal getBalance(BalanceAlarmDTO balanceAlarmDTO) {

        if (StringUtils.equals(PAY_CHANNEL_NAME_YUNHUISUAN, balanceAlarmDTO.getPayChannelName())) {
            // 汇积天下查余额
            return yunHuiSuanService.getBalance();
        } else if (StringUtils.equals(PAY_CHANNEL_NAME_FUSUILINGGONG, balanceAlarmDTO.getPayChannelName())) {
            // 福穗灵工查余额
            return fuSuiLingGongService.getBalance();
        } else {
            XxlJobLogger.log("暂不支持的代付渠道，入参：{}", balanceAlarmDTO.getPayChannelName());
            return null;
        }

    }
}
